package com.ithuangyl.common.web.base;

import android.webkit.JavascriptInterface;

import com.ithuangyl.common.web.event.Event;
import com.ithuangyl.common.web.event.EventManager;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * author : itHuang
 * e-mail : ithuangyl@163.com
 * date   : 2020/6/22 11:45
 */
public class WebInterface {
    private final BaseWebViewActivity activity;

    private WebInterface(BaseWebViewActivity activity) {
        this.activity = activity;
    }

    public static WebInterface create(BaseWebViewActivity activity) {
        return new WebInterface(activity);
    }

    @SuppressWarnings("unused")
    @JavascriptInterface
    public String event() {
        String params = "{'action':'default','message':'this is default event'}";
        try {
            JSONObject jsonObject = new JSONObject(params);
            final String action = jsonObject.getString("action");
            final String text = jsonObject.getString("message");
            final Event event = EventManager.getInstance().getEvent(action);
            if (event != null) {
                event.setAction(action);
                event.setActivity(activity);
                event.setContent(activity);
                event.setUrl(activity.getUrl());
                return event.execute(params);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 这个方法的名字需要跟前端人员协商,建议统一取event,方法的行为可以标注在参数params中
     *
     * @param params：为了标准化，可以让前端人员统一返回一段json字符串， 比如点击h5页面的分享按钮，那么传过来的params就可以写成{action:'share'，id:108}
     *                                           其中action:表示动作，如果有其他的参数如id,可以按需添加
     * @return
     */
    @SuppressWarnings("unused")
    @JavascriptInterface
    public String event(String params) {
        try {
            JSONObject jsonObject = new JSONObject(params);
            final String action = jsonObject.getString("action");
            final String text = jsonObject.getString("message");
            final Event event = EventManager.getInstance().getEvent(action);
            if (event != null) {
                event.setAction(action);
                event.setActivity(activity);
                event.setContent(activity);
                event.setUrl(activity.getUrl());
                return event.execute(params);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
